<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link href="https://adminlte.io/themes/v3/dist/css/adminlte.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <nav class="main-header navbar navbar-expand navbar-white navbar-light">
        <a class="navbar-brand" href="index.php">后台管理</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
    </nav>

    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <div class="sidebar">
            <nav class="mt-2">
                <ul class="nav nav-pills nav-sidebar flex-column">
                    <li class="nav-item">
                        <a href="users.php" class="nav-link">用户管理</a>
                    </li>
                    <li class="nav-item">
                        <a href="tools.php" class="nav-link">小工具管理</a>
                    </li>
                    <li class="nav-item">
                        <a href="call-records.php" class="nav-link">调用记录管理</a>
                    </li>
                    <li class="nav-item">
                        <a href="logout.php" class="nav-link">登出</a>
                    </li>
                </ul>
            </nav>
        </div>
    </aside>

    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>用户管理</h1>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">用户列表</h3>
                                <button type="button" class="btn btn-primary float-right" onclick="showAddUserModal()">新增用户</button>
                            </div>
                            <div class="card-body">
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>用户ID</th>
                                            <th>用户名</th>
                                            <th>余额</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="usersTableBody">
                                        <!-- 用户数据 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- 新增用户模态框 -->
    <div class="modal fade" id="addUserModal" tabindex="-1" role="dialog" aria-labelledby="addUserModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addUserModalLabel">新增用户</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="addUserForm">
                        <div class="form-group">
                            <label for="username">用户名</label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        <div class="form-group">
                            <label for="password">密码</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="addUser()">保存</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editUserModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editUserModalLabel">编辑用户</h5>
                    <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="editUserForm">
                        <input type="hidden" id="userId" name="userId">
                        <div class="form-group">
                            <label for="editUsername">用户名</label>
                            <input type="text" class="form-control" id="editUsername" name="editUsername" required>
                        </div>
                        <div class="form-group">
                            <label for="editPassword">密码</label>
                            <input type="password" class="form-control" id="editPassword" name="editPassword" required>
                        </div>
                        <div class="form-group">
                            <label for="editBalance">余额</label>
                            <input type="number" step="0.01" class="form-control" id="editBalance" name="editBalance" required>
                        </div>
                        <button type="button" class="btn btn-primary" onclick="editUser()">保存</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            fetchUsers();
        });

        function fetchUsers() {
            fetch('get-users.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        var users = data.users;
                        var tableBody = document.getElementById('usersTableBody');
                        tableBody.innerHTML = '';
                        users.forEach(function(user) {
                            var row = `
                                <tr>
                                    <td>${user.id}</td>
                                    <td>${user.username}</td>
                                    <td>${user.balance}</td>
                                    <td>
                                        <button type="button" class="btn btn-primary btn-sm" onclick="showEditUserModal(${user.id})">编辑</button>
                                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteUser(${user.id})">删除</button>
                                    </td>
                                </tr>
                            `;
                            tableBody.innerHTML += row;
                        });
                    } else {
                        document.getElementById('usersTableBody').innerHTML = '<tr><td colspan="4">暂无用户</td></tr>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }

        function showAddUserModal() {
            var addUserModal = new bootstrap.Modal(document.getElementById('addUserModal'));
            addUserModal.show();
        }

        function addUser() {
            var username = document.getElementById('username').value;
            var password = document.getElementById('password').value;

            fetch('add-user.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        var addUserModal = new bootstrap.Modal(document.getElementById('addUserModal'));
                        addUserModal.hide();
                        fetchUsers();
                        alert('用户新增成功');
                    } else {
                        alert('新增失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('请求失败: ' + error);
                });
        }

        function showEditUserModal(userId) {
            fetch(`get-user.php?id=${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        var user = data.user;
                        document.getElementById('userId').value = user.id;
                        document.getElementById('editUsername').value = user.username;
                        document.getElementById('editPassword').value = user.password;
                        document.getElementById('editBalance').value = user.balance;
                        var editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
                        editUserModal.show();
                    } else {
                        alert('获取用户信息失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('请求失败: ' + error);
                });
        }

        function editUser() {
            var userId = document.getElementById('userId').value;
            var username = document.getElementById('editUsername').value;
            var password = document.getElementById('editPassword').value;
            var balance = document.getElementById('editBalance').value;

            fetch('edit-user.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `id=${encodeURIComponent(userId)}&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&balance=${encodeURIComponent(balance)}`,
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        var editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
                        editUserModal.hide();
                        fetchUsers();
                        alert('用户编辑成功');
                    } else {
                        alert('编辑失败: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('请求失败: ' + error);
                });
        }

        function deleteUser(userId) {
            if (confirm('确定要删除此用户吗？')) {
                fetch('delete-user.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `id=${encodeURIComponent(userId)}`,
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            fetchUsers();
                            alert('用户删除成功');
                        } else {
                            alert('删除失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        alert('请求失败: ' + error);
                    });
            }
        }
    </script>
</body>
</html>